package com.chenshu.shop.controller.admin;

import com.chenshu.shop.common.Constant;
import com.chenshu.shop.common.SessionUtil;
import com.chenshu.shop.model.Admin;
import com.chenshu.shop.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2024-06-04
 * Time：10:53
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    AdminService adminService;

    /**
     * 登陆，登陆成功跳转到主页/失败重新登陆
     * @param username
     * @param password
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request) {
        boolean flag = adminService.login(username, password, request);
        if (flag) {
            return "redirect:/admin/index.jsp";
        } else {
            return "redirect:/admin/login.jsp";
        }
    }

    /**
     * 新增管理员 —— 必须在管理员登陆的时候完成
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/adminSave")
    public String adminSave(String username, String password) {
        if (adminService.adminSave(username, password) == 1) {
            return "redirect:/admin/adminList";
        }
        return "redirect:/admin/admin_add.jsp";
    }


    /**
     * 注销：将Session中的SESSION_ADMIN_INFO_KEY删除
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Admin adminInfo = SessionUtil.getLoginAdmin(request);
        //如果管理员有登陆信息，就将Admin的session值置空
        if (adminInfo!=null) {
            session.setAttribute(Constant.SESSION_ADMIN_INFO_KEY, null);
        }
        return "redirect:/admin/login.jsp";
    }

    @RequestMapping("/adminList")
    public String getAdminList(HttpServletRequest request) {
        List<Admin> adminList = adminService.getAllAdmins();
        request.setAttribute("adminList", adminList);
        return "forward:/admin/admin_list.jsp";
    }

    @RequestMapping("/adminDelete")
    public String deleteAdmin(@RequestParam("id") Integer adminId) {
        adminService.deleteAdmin(adminId);
        return "redirect:/admin/adminList";
    }

    @RequestMapping("/redirect/admin_add")
    public String getAdminAddPage() {
        return "redirect:/admin/admin_add.jsp";
    }

    @RequestMapping("/adminReset")
    public String resetAdmin(Integer id, String password) {
        adminService.updateAdminPassword(id, password);
        return "redirect:/admin/adminList";
    }
}
